package isec.amov.tp2.automaintenance;

import java.util.ArrayList;
import java.util.HashMap;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;

public class Maintenance extends Activity {

	private DBAdapter db;
	private ListView lv;
	private Context context;
	

	//Called when the activity is first created
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_maintenance);
		
		context = this;
		db = new DBAdapter(this);
		db.open(this);
		
		lv =(ListView)findViewById(R.id.lvCarros);
		
		SimpleAdapter sa=new SimpleAdapter(this, loadList(), R.layout.lista_carro,
				new String[] {DbHelper.MARCA, DbHelper.MODELO, DbHelper.MATRICULA, DbHelper.QUILOMETROS},
				new int[] {R.id.carMarca,R.id.carModelo,R.id.carMatricula, R.id.carQuilometros});
		lv.setAdapter(sa);
		
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, final int arg2, long arg3) {
				
				
				Log.i("teste", "1");
				Intent intent = new Intent();
				intent.setClass(context,  EditDistance.class);
				intent.putExtra("id", arg2+1);
				startActivity(intent);
				finish();
				Log.i("teste", "2");
			}
		});
		
		if(db!=null){
			db.close();
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_listar_carros, menu);
		return true;
	}
	
	
	private ArrayList<HashMap<String, String>> loadList(){
		
		ArrayList<HashMap<String,String>> carMap = new ArrayList<HashMap<String,String>> ();
		HashMap<String,String> tmpCar;
		Carro car = null;

		Log.i("teste", "num obj: " + db.numCarros());
		for(int i = 1; i < db.numCarros()+1; i++){
			
			car = db.getCarro(i);
			tmpCar = new HashMap<String,String> ();
			tmpCar.put(DbHelper.MARCA, car.getMarca());
			tmpCar.put(DbHelper.MODELO, "" + car.getModelo());
			tmpCar.put(DbHelper.MATRICULA, "" + car.getMatricula());
			tmpCar.put(DbHelper.QUILOMETROS, "" + car.getQuilometros());
			carMap.add(tmpCar);
			Log.i("teste", "carinseridos: " + i);
		}
		
		return carMap;
	}
	
}

